// 全局变量
var today = new Date();
var todayTxt = today.format('yyyy-MM-dd');


var MY_SUMMARIZE = (function() {

	function loadInstitutions(){
		//清除排序
		var  oTable = document.getElementById("dataTable");
		oTable.sortCol = -1;
		//重置全部排序图标
		$("after").css("opacity",0.3);
		$("before").css("opacity",0.3);

		var params = getFromPar();
		if(params){
		var institutionName = $.trim($('#institutionName').val());
		if ( institutionName.length ){
			params.institutionName = institutionName;
		}
		//选择的年月
		//params.dateYm = $('#year').val() + '' + $('#month').val();

		var $tbodyInstitutionList = $('#tbodyInstitutionList');
		$tbodyInstitutionList.empty();

		WeKnow.loading();

		$.ajax({
	        type: "POST",
	        url: "invs_summarize.do/load",
	        dataType: "json",
	        data: params,
	        async: true,//异步调用
	        success: function(data) {

	        	WeKnow.closeLoading();

				if (!WeKnow.filterAjaxResult(data)) return false; // session过期check

	        	if (data.errcode == 0) {
	        		// 把取到的结果放到
	        		var e = '';

	        		if ( 'datalist' in data && data.datalist.length == 0 ){
	        			WeKnow.errorMsg('没有查询到医疗机构数据');
	        			return;
	        		}
					var status = $("#status").val();
					//首行总统计
					var dataLength = 0;
					//权限
					var jurisdiction_invsPrescriptionViolate = $("#jurisdiction_invsPrescriptionViolate").length==0?"style=\"display:none;\"":"";
					var jurisdiction_invsInstrumentDisinfect = $("#jurisdiction_invsInstrumentDisinfect").length==0?"style=\"display:none;\"":"";
					var jurisdiction_invsWasteDelivery = $("#jurisdiction_invsWasteDelivery").length==0?"style=\"display:none;\"":"";
					var jurisdiction_invsSewageTestReport = $("#jurisdiction_invsSewageTestReport").length==0?"style=\"display:none;\"":"";
					var jurisdiction_remotePanel = $("#jurisdiction_remotePanel").length==0?"style=\"display:none;\"":"";
					var jurisdiction_threeDayPanel = $("#jurisdiction_threeDayPanel").length==0?"style=\"display:none;\"":"";
	        		$(data.datalist).each(function( idx,_a){
						//获取状态条件
						if(status == "-1"){
							//存在一个异常就展示
							if(!(_a.prescriptionCheckSt != 0 || _a.disinfectCheckSt != 0 || _a.wasteCheckSt != 0
								|| _a.sewageCheckSt != 0||_a.threeDayCheckSt!=0||_a.remoteCheckSt !=0)){
								return true;
							}
						}else if(status == "-2"){
							//处方外存在一个异常就展示
							if(!(_a.disinfectCheckSt != 0 || _a.wasteCheckSt != 0 || _a.sewageCheckSt != 0
								||_a.threeDayCheckSt!=0||_a.remoteCheckSt !=0)){
								return true;
							}
						}else if(status == "-3"){
							//消毒登记，医废登记，检测审查只要有一个有异常就展示
							if(!(_a.disinfectCheckSt != 0 || _a.wasteCheckSt != 0 || _a.sewageCheckSt != 0)){
								return true;
							}
						}
	        			e+='<tr class="pointer" ';
		        				e+= ' data-institution_id="' + _a.institutionId + '"';
		        				e+= ' data-institution_name="' + _a.institutionName + '"';
	        			e+='>';
        					// 医疗机构名
	        				e+='<td class="text-left">'+  _a.institutionName + '</td>';
							if ( _a.prescriptionCheckSt == 0 ){
								e+='<td class="text-center prescription" '+jurisdiction_invsPrescriptionViolate+'>正常</td>';//处方
							} else {
								e+='<td class="text-center prescription error_st" '+jurisdiction_invsPrescriptionViolate+'>异常('+ _a.prescriptionIllegalCnt + ')</td>';//处方
							}
							if ( _a.remoteCheckSt == 0 ){
								e+='<td class="text-center remote" '+jurisdiction_remotePanel+'>正常</td>';//异地
							} else {
								e+='<td class="text-center remote error_st" '+jurisdiction_remotePanel+'>异常('+ _a.remoteIllegalCnt + ')</td>';//异地
							}
							if ( _a.threeDayCheckSt == 0 ){
								e+='<td class="text-center threeDay" '+jurisdiction_threeDayPanel+'>正常</td>';//三天无处方
							} else {
								e+='<td class="text-center threeDay error_st" '+jurisdiction_threeDayPanel+'>异常('+ _a.threeDayIllegalCnt + ')</td>';//异地
							}
							if ( _a.disinfectCheckSt == 0 ){
								e+='<td class="text-center disinfect" '+jurisdiction_invsInstrumentDisinfect+'>正常</td>';//消毒
							} else {
								e+='<td class="text-center disinfect error_st" '+jurisdiction_invsInstrumentDisinfect+'>异常('+ _a.disinfectIllegalCnt + ')</td>';//消毒
							}
							if ( _a.wasteCheckSt == 0 ){
								e+='<td class="text-center waste" '+jurisdiction_invsWasteDelivery+'>正常</td>';//医废
							} else {
								e+='<td class="text-center waste error_st" '+jurisdiction_invsWasteDelivery+'>异常('+ _a.wasteIllegalCnt + ')</td>';//医废
							}
							if ( _a.sewageCheckSt == 0 ){
								e+='<td class="text-center sewage" '+jurisdiction_invsSewageTestReport+'>正常</td>';//污水
							} else {
								e+='<td class="text-center sewage error_st" '+jurisdiction_invsSewageTestReport+'>异常('+ _a.sewageIllegalCnt + ')</td>';//污水
							}
	        				// 相关记录
	        				e+='<td class="text-center">';
		        				e+='<button type="button" name="showDetail" class="btn btn-default btn-sm">查看记录</button>';
		        			e+='</td>';
	        			e+='</tr>';
						dataLength += 1;
	        		});
	        		//添加首行记录数
					var firstTr = "";
					firstTr += '<tr class="pointer" style="background-color:#E0FFFF;">';
					firstTr += '<td class="text-left">总机构数：' + dataLength + '</td>';
					firstTr += '<td class="text-center" '+jurisdiction_invsPrescriptionViolate+'></td>';
					firstTr += '<td class="text-center" '+jurisdiction_remotePanel+'></td>';
					firstTr += '<td class="text-center" '+jurisdiction_threeDayPanel+'></td>';
					firstTr += '<td class="text-center" '+jurisdiction_invsInstrumentDisinfect+'></td>';
					firstTr += '<td class="text-center" '+jurisdiction_invsWasteDelivery+'></td>';
					firstTr += '<td class="text-center" '+jurisdiction_invsSewageTestReport+'></td>';
					firstTr += '<td class="text-center"></td>';
					firstTr += '</tr>';
					e = firstTr + e;
	        		$tbodyInstitutionList.append(e);
	        	} else if (data.errcode == -1 ) {
	        		WeKnow.errorMsg( data.errMsg );
	        	} else {
	        		WeKnow.systemMsg('查询失败，请重新登录后再试');
	        	}
	        }
		});
	}}


	/** 获取页面输入参数 */
	function getFromPar(){
		var data = {};

		// 标本日期 from - to
		var $dtFrom = $('#dtFrom');
		if ( !$dtFrom.val().length ){
			WeKnow.errorMsg('请输入查询开始日期');
			$dtFrom.focus();
			return false;
		}

		var dtFrom = $dtFrom.val();
		if ( !MY_VALIDATOR.isDate(dtFrom,'yyyy-MM-dd')){
			WeKnow.errorMsg('查询开始日期格式不正确');
			$dtFrom.focus();
			return false;
		}
		data.dtFrom = dtFrom;

		// 查询日期to
		var $dtTo = $('#dtTo');
		if ( !$dtTo.val().length ){
			WeKnow.errorMsg('请输入查询结束日期');
			$dtTo.focus();
			return false;
		}

		var dtTo = $dtTo.val();
		if ( !MY_VALIDATOR.isDate(dtTo,'yyyy-MM-dd')){
			WeKnow.errorMsg('查询结束日期格式不正确');
			$dtTo.focus();
			return false;
		}
		data.dtTo = dtTo;

        if($dtFrom.val()>$dtTo.val()){
            WeKnow.errorMsg('开始时间不能大于结束时间');
            return false;
        }
		// 地区ID
		var townId =  $('#townId').val();
		if ( townId.length ){
			data.townId = townId;
		}
		var institutionTypeFirstScreen =  $('#institutionTypeFirstScreen').val();
		if ( institutionTypeFirstScreen.length ){
			data.institutionTypeFirst = institutionTypeFirstScreen;
		}

		return data;
	}

	/**
	 * 根据type、查询对应的内容。并作显示控制
	 */
	function loadOneTypeInfo(){

		var operateType = parseInt ( $('#operateType').val());
		var institutionId = $('#institutionId').val();

		switch(operateType) {
			case 1://处方
				// 页面初期数据查询
				var $thead= $('thead#thead-prescription');
				var $tbody= $('tbody#tbody-prescription');// 明细
				var params = MY_SM_PRESCRIPTION_VIOLATE.getParams();
				MY_PRESCRIPTION_VIOLATE_COM.loadDetailItem(params,$thead,$tbody);


				$('#prescription_sec').show();
				break;

			case 3://消毒
				// 默认选中器械消毒
				//$('select.business-sub-type').find("option[value='101']").prop("selected",true);
				// $('section#instrument_disinfect_sec').find('select[name="businessSubType"]').val(101);
				// $('#businessSubType').val(101);
				// 初始化器械列表
				MY_SM_INSTRUMENT_DISINFECT.loadInstrumentList();

				var $tHead  = $('#tHeadDisinfectDetailList');
				var $tbody = $('#tbodyDisinfectDetailList');
				var params = MY_SM_INSTRUMENT_DISINFECT.getDetailParams();
				MY_INSTRUMENT_DISINFECT_COMMON.loadDetailItem(params, $tHead, $tbody);
				$('#instrument_disinfect_sec').show();
	            break;
	       case 4:

			   // 初始来源列表
			   MY_SM_WASTE_DELIVERY.loadInstrumentList();

	    	    var $tHead  = $('#waste_thead');
	    		var $tbody = $('#waste_tbody');
	    		var params = MY_SM_WASTE_DELIVERY.getDetailParams();
	    		MY_WASTE_DELIVERY_COM.loadDetailItem(params,$tHead,$tbody);
	   			$('#waste_delivery_sec').show();
	            break;
	       case 5:

	    	   var $thead = $('#test_report_thead');
           		var $tbody = $('#test_report_tbody');

	            var businessSubType = $('#test_sec').find('select[name="businessSubType"]').val();
	            if ( businessSubType == 301 || businessSubType == 303  ){//医疗污水检测报告
            		var params = MY_SM_SEWAGE_TEST_REPORT.getParams();
            		MY_SEWAGE_TEST_REPORT_COM.loadItem(params,$thead,$tbody);
	            } else  if ( businessSubType == 302 ){//污水余氯日常检测
	        		var params = MY_SM_SEWAGE.getDetailParams();
	        		MY_SEWAGE_COM.loadDetailItem(params,$thead,$tbody);
	            }
	            $('#test_sec').show();
	            break;
			case 6://异地执业
				var $thead= $('thead#thead-remote');
				var $tbody= $('tbody#tbody-remote');// 明细
				var params = MY_SM_REMOTE.getParams();
				MY_REMOTE_COM.loadDetailItem(params,$thead,$tbody);
				$('#remote_sec').show();
				break;
			case 7://三天无处方
				var $thead= $('thead#thead-threeDay');
				var $tbody= $('tbody#tbody-threeDay');// 明细
				var params = MY_SM_threeDay.getParams();
				MY_THREEDAY_COM.loadDetailItem(params,$thead,$tbody);
				$('#threeDay_sec').show();
				break;
	        default:
	        	WeKnow.errorMsg("未能识别的状态！");
	        	break;
		}
	}

	// 各业务数据状态查询
	function getSummarize(){

		var institutionId = $('#institutionId').val();

        var params = getFromPar();
		if(params) {
            params.institutionId = institutionId;
            //params.dateYm = $('#year').val() + '' + $('#month').val();

            WeKnow.loading();

            $.ajax({
                type: "POST",
                url: "invs_summarize.do/load_one_sum",
                dataType: "json",
                data: params,
                async: true,//异步调用
                success: function (data) {

                    WeKnow.closeLoading();

                    if (!WeKnow.filterAjaxResult(data)) return false; // session过期check

                    if (data.errcode == 0) {

                        var _a = data.resModel;
                        // 处方
                        if (_a.prescriptionCheckSt == 0) {
                            $('#prescription_dis').text('正常');
                            $('#prescription_dis').css('color', '');
                        } else {
                            $('#prescription_dis').text('异常(' + _a.prescriptionIllegalCnt + ')');
                            $('#prescription_dis').css('color', 'red');
                        }
						//异地执业
						if (_a.remoteCheckSt == 0) {
							$('#remote_dis').text('正常');
							$('#remote_dis').css('color', '');
						} else {
							$('#remote_dis').text('异常(' + _a.remoteIllegalCnt+ ')');
							$('#remote_dis').css('color', 'red');
						}
						//三天无处方
						if (_a.threeDayCheckSt == 0) {
							$('#threeDay_dis').text('正常');
							$('#threeDay_dis').css('color', '');
						} else {
							$('#threeDay_dis').text('异常(' + _a.threeDayIllegalCnt+ ')');
							$('#threeDay_dis').css('color', 'red');
						}
                        //消毒
                        if (_a.disinfectCheckSt == 0) {
                            $('#instrument_disinfect_dis').text('正常');
                            $('#instrument_disinfect_dis').css('color', '');
                        } else {
                            $('#instrument_disinfect_dis').text('异常(' + _a.disinfectIllegalCnt + ')');
                            $('#instrument_disinfect_dis').css('color', 'red');
                            //设置默认
							if(_a.disinfectIllegalCntA == 0 && _a.disinfectIllegalCntB > 0){
								//101异常为0 则 默认为102
								$('section#instrument_disinfect_sec').find('select[name="businessSubType"]').val(102);
							}else{
								$('section#instrument_disinfect_sec').find('select[name="businessSubType"]').val(101);
							}
                        }
						//医废
                        if (_a.wasteCheckSt == 0) {
                            $('#waste_delivery_dis').text('正常');
                            $('#waste_delivery_dis').css('color', '');
                        } else {
                            $('#waste_delivery_dis').text('异常(' + _a.wasteIllegalCnt + ')');//医废
                            $('#waste_delivery_dis').css('color', 'red');
                        }
                        //污水
                        if (_a.sewageCheckSt == 0) {
                            $('#sewage_dis').text('正常');
                            $('#sewage_dis').css('color', '');
                        } else {
                            $('#sewage_dis').text('异常(' + _a.sewageIllegalCnt + ')');
                            $('#sewage_dis').css('color', 'red');
							//设置默认
							if(_a.sewageIllegalCntA == 0 && _a.sewageIllegalCntB > 0){
								//301异常为0 则 默认为302
								$('#test_sec').find('select[name="businessSubType"]').val(302);
							}else if(_a.sewageIllegalCntB == 0 && _a.sewageIllegalCntC > 0){
								//302异常为0 则 默认为303
								$('#test_sec').find('select[name="businessSubType"]').val(303);
							}
                        }
                    } else if (data.errcode == -1) {
                        WeKnow.errorMsg(data.errMsg);
                    } else {
                        WeKnow.systemMsg('查询失败，请重新登录后再试');
                    }
                }
            });
        }
	}

	// add by zhengxb 2019.6.21  end ---------------------------------------------------------
	return {
		loadInstitutions:loadInstitutions,
		loadOneTypeInfo:loadOneTypeInfo,
		getSummarize:getSummarize
	}
})();
var map = undefined;
var marker = undefined;
$(document).ready(function() {

	// 页面初期数据查询
	MY_SUMMARIZE.loadInstitutions();

	//查询按钮按下
	$('#search').on('click',function(){
		MY_SUMMARIZE.loadInstitutions();
	});
	$('select.business-sub-type').change(function () {
		// 查询器械或场所列表
		MY_SM_INSTRUMENT_DISINFECT.loadInstrumentList();
	});
	$('select[name="institutionTypeFirstScreen"]').on('change',function(){
		MY_SUMMARIZE.loadInstitutions();
	});


	var scrollTop = 0;

	// 查看记录
	$('#tbodyInstitutionList').on('click','button[name="showDetail"]',function(){
		var $that = $(this);
		var $parentTr = $that.closest('tr');
		//记住当前位置
		scrollTop = $(window).scrollTop();
		$('.toggle-input').toggle();//主页面·详细页面切换显示
		//记住选中的机构Id
		var institutionId = $parentTr.data('institution_id');
		$('#institutionId').val(institutionId);
		// 显示选中的机构名
		var institutionName = $parentTr.data('institution_name');
		// $('#year_month').text('（' + $('#year').val() + '年' + $('#month').val() + '月）');
        $('#year_month').text('（' + $('#dtFrom').val() + ' 至 ' + $('#dtTo').val() + '）');
		$('#institution_name_dis').text(institutionName);
		// 第一个tab显示
		$('.div_tab_panel :visible:first').click();
	});

	// 备案信息  
	$('#tbodyInstitutionList').on('click','button[name="archival"]',function(){
		var $that = $(this);
		var $parentTr = $that.closest('tr');

		$('.toggle_doctot_register_info').toggle();//主页面·备案信息页面切换显示
		//记住选中的机构Id
		var institutionId = $parentTr.data('institution_id');
		$('#institutionId').val(institutionId);
		// 显示选中的机构名
		var institutionName = $parentTr.data('institution_name');
		$('#institution_name_register_dis').text(institutionName);
		// 查询医疗机构对应的医生
		MY_SM_DOCTOR_ARCHIVAL.loadDoctors();
	});

	// 回退
	$('#backToWorkspace').on('click',function(){
		$('.toggle-input').toggle();//主页面·详细页面切换显示
		//滚动条回到原位置
		$(window).scrollTop(scrollTop);
	});
	//主页面·备案页面切换显示
	$('#backToWorkspaceDoctor').on('click',function(){
		// 页面显示
		$('.toggle_doctot_register_info').toggle();
	});
	// panel切换
	$('.div_tab_panel').on('click',function(){
		var $that = $(this);
		// 记住点了哪个TAB
		$('#operateType').val($that.data('operate_idx'));
		// 选中TAB变换成高亮样式
		$('.active_tab').removeClass('active_tab');
		$that.addClass('active_tab');
		// 已显示出来的明细section隐藏掉
		$('section.detail_area').hide();
		MY_SUMMARIZE.getSummarize();//刷新各TAB的总件数
		// 显示对应tab的内容
		MY_SUMMARIZE.loadOneTypeInfo();
	});

	$('#year,#month').on('change',function(){
		// 数据查询
		MY_SUMMARIZE.loadInstitutions();

	});

	$(".my_date_control" ).datepicker({
		changeMonth: true,
		changeYear: true,
		dateFormat: 'yy-mm-dd',//日期格式
		yearSuffix: '年', //年的后缀
		showMonthAfterYear:true,//是否把月放在年的后面
		maxDate: (function() {
			return todayTxt;
		})(),//最大日期
		yearRange: (function() {
			// '1990:2010'
			var year1 = '1900';
			var year2 = today.getFullYear();
			return year1 + ':' + year2;
		})(),
		monthNamesShort: ['01','02','03','04','05','06','07','08','09','10','11','12'],
		dayNamesMin: ['日','一','二','三','四','五','六'],
		onUpdatedDatepicker: function(_year, _month, _calendar) {
			console.log('onUpdatedDatepicker');
			var $c = $('div#ui-datepicker-div');
			$c.find('td[data-handler="selectDay"]').each(function(idx, d) {
				var $d = $(d);
				$d.css({'pointer-events': 'auto', 'opacity': 1});
			});
		}
	});


		// Bmap初始化
		$("#container").empty();
		// alert($("#container").html());
		map = new BMap.Map("container");
		map.enableScrollWheelZoom();   //启用滚轮放大缩小，默认禁用
		map.enableContinuousZoom();
		map.addControl(new BMap.NavigationControl());
		map.addControl(new BMap.NavigationControl());
		map.addControl(new BMap.ScaleControl());
		map.addControl(new BMap.OverviewMapControl());
		map.addControl(new BMap.MapTypeControl());
	});

	// 显示地图
	$('#tbody-remote').on('click','button[name="showLocation"]',function(){
		$(".modal").modal("hide");
		$("#showMapModal").modal("show");
		var loginPositionStr = $(this).attr("loginPosition");
		var local=loginPositionStr.split(',');
		// alert(local[0]+":"+local[1]);
		// alert($("#container").html());
		var point = new BMap.Point(local[0], local[1]);
		marker = new BMap.Marker(point);        // 创建标注
		map.addOverlay(marker);
		// alert(JSON.stringify(point));
		map.centerAndZoom(point, 15);
		map.panBy(400,350);

		// map.setCurrentCity("北京"); // 仅当设置城市信息时，MapTypeControl的切换功能才能可用

	});
	$('body').on('hidden.bs.modal', '.modal', function () {
		$(this).removeData('bs.modal');
		if (marker) {
			map.removeOverlay(marker);
			map.panBy(-400, -350);
		}
	});
// $('#showMapModal').on('hidden.bs.modal', function (e) {
// 	//$(this).removeData('bs.modal');
// });
